<template>
  <!-- 新增编辑查看弹出框 -->
  <el-dialog :title="dialogTitle" v-model="editVisible" width="60%" :close-on-click-modal="closeOnClickModal" draggable @closed="closedFormDialog">
    <el-form ref="formRef" :model="form" :rules="rules" v-loading="loading" label-width="150px">
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="场景：" prop="scenario">
            <el-select v-model.trim="form.scenario" placeholder="场景" clearable>
              <el-option v-for="item in selectMap" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="分类名称：" prop="name">
            <el-input v-model.trim="form.name" placeholder="分类名称"> </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="主图：" prop="image">
            <UploadImageInfo v-model:disabledbtn="disabledbtn" v-model:loading="loading" imageKey="image" v-model:form="form" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="排序：" prop="sort">
            <el-input v-model.trim.number="form.sort" placeholder="排序"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button :disabled="disabledbtn" @click="formStatus = 'none'">取 消</el-button>
        <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import UploadImageInfo from "@/components/common/UploadImageInfo.vue";
import type { postOrPutType } from "@/constants";
import type { ViewMode } from "@/types/common";
import { useState } from "@/hooks/useState.ts";
import type { IFaqCategory } from "@/types/problemManage/faqCategory";
import type { IDictData } from "@/types/dict";
import { commonFaqCategoryInfo } from "@/utils/api/faqCategory";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  selectMap: Array<IDictData>;
}
const { selectMap } = defineProps<Props>();
const emit = defineEmits<{
  handleSuccess: [];
}>();
const formStatus = defineModel<ViewMode>("formStatus", { required: true });
const form = defineModel<IFaqCategory>("form", { required: true });

const editVisible = ref(false);
const formRef = useTemplateRef("formRef");

const rules = reactive({
  name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
  scenario: [{ required: true, message: "请选择场景", trigger: "blur" }],
  sort: [{ required: true, message: "请输入排序顺序", trigger: "blur" }]
});

const dialogTitle = ref("新增");
const methodType = ref<postOrPutType>("POST");
const usernameDisabled = ref(false);
const closeOnClickModal = ref(false);
const isDisabledbtn = ref(false);
/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    dialogTitle.value = "查看";
    editVisible.value = true;
    isDisabledbtn.value = true;
    closeOnClickModal.value = true;
  },
  edit: () => {
    dialogTitle.value = "编辑";
    methodType.value = "PUT";
    editVisible.value = true;
    usernameDisabled.value = false;
  },
  add: () => {
    dialogTitle.value = "新增";
    methodType.value = "POST";
    editVisible.value = true;
    usernameDisabled.value = false;
  },
  none: () => {
    dialogTitle.value = "新增";
    methodType.value = "POST";
    editVisible.value = false;
    usernameDisabled.value = false;
    isDisabledbtn.value = false;
    closeOnClickModal.value = false;
    form.value.id = 0;
    formRef.value?.resetFields();
    formRef.value?.clearValidate();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});

// 关闭模态框
function closedFormDialog() {
  changeFormStatus("none");
}
// 切换formStatus
function changeFormStatus(state: ViewMode) {
  formStatus.value = state;
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  toggleState(true);
  commonFaqCategoryInfo(form.value, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      changeFormStatus("none");
      emit("handleSuccess");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
</script>

<style lang="scss" scoped>
/* 修改select的盒模型 */
.el-select {
  display: block;
}
</style>
